<template>
  <div>
    <base-modal
      :title="$t('common.base.bulkEdit')"
      :show.sync="visible"
      width="524px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        
        label-position="top"
        class="edit-form"
      >
        <el-form-item :label="$t('common.base.modifyField')" prop="fields">
          <el-select v-model="editForm.fields" style="width: 90%">
            <el-option
              v-for="item in ModifyFieldsOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 修改商品名称 -->
        <template v-if="editForm.fields === 'commodityName'">
          <el-form-item :label="$t('goods.component.tradeName')" prop="nameType">
            <el-radio-group v-model="editForm.nameType">
              <el-radio label="1">{{$t('goods.component.addPrefixorSuffix')}}</el-radio>
              <el-radio label="2">{{$t('goods.component.alternateName')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <template v-if="editForm.nameType === '1'">
              <el-form-item>
                <span
                  >{{$t('goods.component.tipText')}}</span
                >
              </el-form-item>
              <el-form-item :label="$t('goods.component.prefix')">
                <el-input
                  v-model="editForm.prefixName"
                  style="width: 60%"
                  maxlength="20"
                ></el-input>
              </el-form-item>
              <el-form-item :label="$t('goods.component.suffix')">
                <el-input
                  v-model="editForm.suffixName"
                  style="width: 60%"
                  maxlength="20"
                ></el-input>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item>
                <span
                  >{{$t('goods.component.replaceText')}}</span
                >
              </el-form-item>
              <el-form-item :label="$t('goods.component.originalText')">
                <el-input
                  v-model="editForm.fromNameStr"
                  style="width: 60%"
                  maxlength="20"
                ></el-input>
              </el-form-item>
              <el-form-item :label="$t('goods.component.replace')">
                <el-input
                  v-model="editForm.toNameStr"
                  style="width: 60%"
                  maxlength="20"
                ></el-input>
              </el-form-item>
            </template>
          </el-form-item>
        </template>

        <!-- 修改价格 -->
        <template v-else-if="editForm.fields === 'price'">
          <el-form-item :label="$t('goods.component.pricingMethod')" prop="priceType">
            <el-radio-group
              v-model="editForm.priceType"
              class="edit-form-radio"
            >
              <div class="edit-form-radio-item">
                <el-radio label="1">{{$t('goods.component.originalPriceIncrease')}}</el-radio>
                <div v-if="editForm.priceType === '1'">
                  <span>{{$t('goods.component.priceRule1')}} </span>
                  <el-input-number
                    v-model="editForm.rate1"
                    :controls="false"
                    :precision="2"
                    :max="99.99"
                    :min="0"
                    :placeholder="$t('goods.component.ratio')"
                  ></el-input-number>
                  <span>%）</span>
                </div>
              </div>
              <div class="edit-form-radio-item">
                <el-radio label="2">{{$t('goods.component.originalPriceDecrease')}}</el-radio>
                <div v-if="editForm.priceType === '2'">
                  <span>{{$t('goods.component.priceRule2')}} </span>
                  <el-input-number
                    v-model="editForm.rate2"
                    :controls="false"
                    :precision="2"
                    :max="99999"
                    :min="0"
                    :placeholder="$t('goods.component.ratio')"
                  ></el-input-number>
                  <span>%）</span>
                </div>
              </div>
              <div class="edit-form-radio-item">
                <el-radio label="3">{{$t('goods.component.increaseByFixed')}}</el-radio>
                <div v-if="editForm.priceType === '3'">
                  <span>{{$t('goods.component.priceRule3')}} </span>
                  <el-input-number
                    v-model="editForm.price1"
                    :controls="false"
                    :precision="2"
                    :max="99999"
                    :min="0.01"
                    :placeholder="$t('goods.component.fixedAmount')"
                  ></el-input-number>
                </div>
              </div>
              <div class="edit-form-radio-item">
                <el-radio label="4">{{$t('goods.component.dncreaseByFixed')}}</el-radio>
                <div v-if="editForm.priceType === '4'">
                  <span>{{$t('goods.component.priceRule4')}} </span>
                  <el-input-number
                    v-model="editForm.price2"
                    :controls="false"
                    :precision="2"
                    :max="99999"
                    :min="0.01"
                    :placeholder="$t('goods.component.fixedAmount')"
                  ></el-input-number>
                </div>
              </div>
              <div class="edit-form-radio-item">
                <el-radio label="5">{{$t('goods.component.changeToFixed')}}</el-radio>
                <div v-if="editForm.priceType === '5'">
                  <el-input-number
                    v-model="editForm.price3"
                    :controls="false"
                    :precision="2"
                    :max="99999"
                    :min="0"
                    :placeholder="$t('goods.component.fixedAmount')"
                  ></el-input-number>
                </div>
              </div>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('goods.component.precisionProcessing')" prop="precisionType">
            <el-radio-group
              v-model="editForm.precisionType"
              class="edit-form-radio"
            >
              <el-radio label="3" class="edit-form-radio-item"
                >{{$t('goods.component.roundedToCent')}}</el-radio
              >
              <el-radio label="2" class="edit-form-radio-item"
                >{{$t('goods.component.roundedToCorner')}}</el-radio
              >
              <el-radio label="1" class="edit-form-radio-item"
                >{{$t('goods.component.roundedToYuan')}}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </template>

        <!-- 修改库存 -->
        <template v-else>
          <el-form-item :label="$t('common.part.stock')" prop="inventoryNumber">
            <el-input-number
              v-model="editForm.inventoryNumber"
              :min="0"
              :max="99999"
              :step="1"
              step-strictly
              controls-position="right"
            ></el-input-number>
          </el-form-item>
          <span>{{$t('goods.tips.inventoryTip')}}</span>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading"
          >{{$t('common.base.makeSure')}}</el-button
        >
      </div>
    </base-modal>
  </div>
</template>

<script>
import { batchUpdateGoods } from '@src/api/PortalApi.ts';

export default {
  props: {
    selectedIds: {
      type: Array,
      default: () => [],
    },
    multipleSelection: {
      type: Array,
      default: () => [],
    },
  },
  emits: ['reloadPage'],
  data() {
    return {
      visible: false,
      loading: false,
      editForm: {
        fields: 'commodityName',
        nameType: '1',
        prefixName: '',
        suffixName: '',
        fromNameStr: '',
        toNameStr: '',
        priceType: '1',
        rate1: '',
        rate2: '',
        price1: '',
        price2: '',
        price3: '',
        precisionType: '3',
        inventoryNumber: 99999,
      },
      rules: {
        fields: [
          { required: true, message: this.$t('goods.placeHolder.selectModifyField'), trigger: 'change' },
        ],
        nameType: [
          { required: true, message: this.$t('goods.placeHolder.selectModifyMethod'), trigger: 'change' },
        ],
        priceType: [
          { required: true, message: this.$t('goods.placeHolder.selectPricingMethod'), trigger: 'change' },
        ],
        precisionType: [
          { required: true, message: this.$t('goods.placeHolder.selectPrecisionProcess'), trigger: 'change' },
        ],
        inventoryNumber: [
          { required: true, message: this.$t('goods.placeHolder.selectInventory'), trigger: 'blur' },
        ],
      },
      ModifyFieldsOption: [
        { label: this.$t('goods.component.tradeName'), value: 'commodityName' },
        { label: this.$t('common.base.price'), value: 'price' },
        { label: this.$t('common.part.stock'), value: 'inventoryNumber' },
      ],
      selectNoSpescId: []
    };
  },
  methods: {
    open() {
      if (!this.selectedIds.length) {
        return this.$platform.alert(this.$t('goods.placeHolder.selectEditedGoods'));
      }

      this.visible = true;
    },
    // 手动校验某些值
    handleValidate() {
      if (this.editForm.fields === 'commodityName') {
        // 如果修改商品名称，选择前缀和后缀，两个都为空就报错
        if (
          this.editForm.nameType === '1' &&
          !this.editForm.prefixName &&
          !this.editForm.suffixName
        ) {
          this.$message({
            message: this.$t('goods.placeHolder.selectPrefixorSuffix'),
            type: 'warning',
          });

          return false;
        }

        // 如果修改商品名称，选择替换名称，原有文字为空就报错
        if (this.editForm.nameType === '2' && !this.editForm.fromNameStr) {
          this.$message({
            message: this.$t('goods.placeHolder.enterOriginalText'),
            type: 'warning',
          });

          return false;
        }
      }

      if (this.editForm.fields === 'price') {
        // 如果修改价格，选择按原价比例修改，比率为空就报错
        if (
          (this.editForm.priceType === '1' && !this.editForm.rate1) ||
          (this.editForm.priceType === '2' && !this.editForm.rate2)
        ) {
          this.$message({
            message: this.$t('goods.placeHolder.enterRatio'),
            type: 'warning',
          });

          return false;
        }

        // 如果修改价格，选择按固定金额修改，固定金额为空就报错
        if (
          (this.editForm.priceType === '3' && !this.editForm.price1) ||
          (this.editForm.priceType === '4' && !this.editForm.price2)
        ) {
          this.$message({
            message: this.$t('goods.placeHolder.enterFixedAmount'),
            type: 'warning',
          });

          return false;
        }

        // 如果修改价格，选择按固定价格修改，固定价格为空就报错
        if (this.editForm.priceType === '5' && !this.editForm.price3) {
          this.$message({
            message: this.$t('goods.placeHolder.enterModifiedPrice'),
            type: 'warning',
          });

          return false;
        }
      }

      return true;
    },
    handleConfirm() {
      this.$refs.editFormRef.validate(valid => {
        if (valid && this.handleValidate()) {
          this.handleUpdate();
        }
      });
    },
    async handleUpdate() {
      try {
        const params = this.getParams();
        const { code } = await batchUpdateGoods(params);

        if (code !== '200') {
          return this.$message.error(this.$t('goods.component.batchEditingFailed'));
        }

        this.visible = false;
        this.$message.success(this.$t('common.base.tip.bulkEditSuccess'));
        this.editForm = this.$options.data.call(this).editForm;
        this.$emit('reloadPage');
      } catch (error) {
        console.error('update order error', error);
      }
    },
    getParams() {
      const params = {
        ids: this.selectedIds,
      };

      if (this.editForm.fields === 'commodityName') {
        if (this.editForm.nameType === '1') {
          params.name = {
            type: ~~this.editForm.nameType,
            prefixName: this.editForm.prefixName,
            suffixName: this.editForm.suffixName,
          };
        } else {
          params.name = {
            type: ~~this.editForm.nameType,
            fromNameStr: this.editForm.fromNameStr,
            toNameStr: this.editForm.toNameStr,
          };
        }
      }

      if (this.editForm.fields === 'price') {
        if (
          this.editForm.priceType === '1' ||
          this.editForm.priceType === '2'
        ) {
          let proportion =
            Number(this.editForm[`rate${this.editForm.priceType}`]) / 100;
          params.price = {
            type: ~~this.editForm.priceType,
            precisionType: ~~this.editForm.precisionType,
            proportion,
          };
        } else {
          let fixedPrice;
          if (this.editForm.priceType === '3') {
            fixedPrice = this.editForm.price1;
          } else if (this.editForm.priceType === '4') {
            fixedPrice = this.editForm.price2;
          } else {
            fixedPrice = this.editForm.price3;
          }

          params.price = {
            type: ~~this.editForm.priceType,
            precisionType: ~~this.editForm.precisionType,
            fixedPrice: Number(fixedPrice),
          };
        }
      }

      if (this.editForm.fields === 'inventoryNumber') {
        this.selectNoSpescId = this.multipleSelection.filter(v => v.hasSpecs !==1).map(item => item.id) || [];
        if(!this.selectNoSpescId.length) return this.$message.error(this.$t('goods.tips.inventoryTip'));
        params.inventory = {
          inventoryNumber: Number(this.editForm.inventoryNumber),
        };
      }

      return params;
    },
  },
};
</script>

<style lang="scss" scoped>
.edit-form {
  padding: 20px 30px;

  span {
    font-size: 12px;
    font-weight: 400;
    color: #8c8c8c;
    margin-bottom: 20px;
  }

  &-radio {
    display: flex;
    flex-direction: column;

    &-item {
      margin: 8px 0;

      span {
        color: #595959;
      }

      .el-radio {
        margin-bottom: 8px;
      }

      .el-input,
      .el-input-number {
        width: 80px;
        margin: 0 8px;
      }

      .el-input:last-child,
      .el-input-number:last-child {
        width: 100px;
      }

      .el-input:first-child,
      .el-input-number:first-child {
        width: 160px;
      }
    }

    &-item:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
